/**
 * @file debug.c
 *
 * @copyright This file creat by rensuiyi ,all right reserve!
 *
 * @author rensuyi
 *
 * @date 2013/12/21 11:20:50
 */

#include "debug.h"
#include "includes.h"
#include <stdarg.h>

//! @option  debug buffer size
#ifndef DEBUG_BUFFER_SIZE
#define DEBUG_BUFFER_SIZE      (1024)
#endif /* DEBUG_BUFFER_SIZE */

static char m_debug_buffer[DEBUG_BUFFER_SIZE];

struct st_debug_describe {
  debug_stream_t stream;
  uint8_t level;
};

static struct st_debug_describe m_debug =
{
  NULL,
  DEBUG_INFO,
};

int debug_init(debug_stream_t stream, uint8_t level) {
  m_debug.level = level;
  m_debug.stream = stream;
  return 0;
}

uint8_t debug_set_level(uint8_t level) {
  uint8_t previous = m_debug.level;
  m_debug.level = level;
  return previous;
}

uint8_t debug_get_level(uint8_t level) {
  return m_debug.level;
}

debug_stream_t debug_set_stream(debug_stream_t stream) {
  debug_stream_t preivous = m_debug.stream;
  m_debug.stream = stream;
  return preivous;
}

debug_stream_t debug_get_stream(void) {
  return m_debug.stream;
}

void debug(uint8_t level, char* fmt, ...) {
  va_list va_args;
  int len;

  // if the level lower,skip
  if (level < m_debug.level) {
    return;
  }

  va_start(va_args, fmt);
  len = vsnprintf(m_debug_buffer, DEBUG_BUFFER_SIZE, fmt, va_args);
  va_end(va_args);

  if ((len != 0) && (m_debug.stream != NULL)) {
    m_debug.stream(m_debug_buffer, len);
  }
}
